package com.baoyouqun.service.impl;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.DemandCollectionCreateCmd;
import com.baoyouqun.domain.Enum.DemandCollectionStatusEnum;
import com.baoyouqun.domain.Enum.DemandCollectionTypeEnum;
import com.baoyouqun.domain.Query.DemandCollectionQuery;
import com.baoyouqun.domain.UpdateCmd.DemandCollectionUpdateCmd;
import com.baoyouqun.domain.VO.DemandCollectionVO;
import com.baoyouqun.entity.DemandCollection;
import com.baoyouqun.mapper.DemandCollectionMapper;
import com.baoyouqun.service.DemandCollectionService;
import com.baoyouqun.service.DemandService;
import jakarta.annotation.Resource;
import org.apache.poi.util.StringUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class DemandCollectionServiceImpl extends ServiceImpl<DemandCollectionMapper, DemandCollection> implements DemandCollectionService {

    @Resource
    private DemandCollectionMapper demandCollectionMapper;
    @Resource
    @Lazy
    private DemandService demandService;

    @Override
    public SingleResponse<DemandCollectionVO> create(DemandCollectionCreateCmd cmd) {
        DemandCollection entity =
                ConvertUtils.copyBean(cmd, DemandCollection.class);
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        DemandCollectionVO vo =
                ConvertUtils.copyBean(entity, DemandCollectionVO.class);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(DemandCollectionUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        DemandCollection oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        oldEntity = ConvertUtils.copyBean(cmd, DemandCollection.class);
        Boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public DemandCollectionVO selectById(String id) {
        DemandCollection entity = demandCollectionMapper.selectById(id);
        DemandCollectionVO vo =
                ConvertUtils.copyBean(entity, DemandCollectionVO.class);
        return vo;
    }

    @Override
    public IPage<DemandCollectionVO> pageVo(DemandCollectionQuery query) {
        IPage<DemandCollection> page = new Page<DemandCollection>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<DemandCollection>());
        Page<DemandCollectionVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<DemandCollectionVO> records = ConvertUtils.copyBeanList(page.getRecords(), DemandCollectionVO.class);
        voPage.setRecords(records);
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response operate(DemandCollectionCreateCmd cmd) {
        String demandId = cmd.getDemandId();
        String userId = cmd.getUserId();
        DemandCollectionTypeEnum type = cmd.getType();
        LocalDateTime now = LocalDateTime.now();


        // 查询用户是否已有相同类型的有效操作记录
        LambdaQueryWrapper<DemandCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandCollection::getDemandId, demandId)
                .eq(DemandCollection::getUserId, userId);
        DemandCollection existRecord = demandCollectionMapper.selectOne(queryWrapper);

        if (existRecord == null) {
            // 新增交互记录（默认有效状态）
            DemandCollection newRecord = new DemandCollection();
            newRecord.setDemandId(demandId);
            newRecord.setUserId(userId);
            newRecord.setType(type);
            newRecord.setStatus(DemandCollectionStatusEnum.VALID);
            newRecord.setCreateTime(now);
            newRecord.setUpdateTime(now);
            demandCollectionMapper.insert(newRecord);
            // 更新需求表计数（+1）
            demandService.updateDemandCollectionCount(demandId, type, 1);
        }
        return Response.buildSuccess();

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response cancel(String demandId, String userId) {
        LocalDateTime now = LocalDateTime.now();

        // 查询用户对该需求的有效交互记录
        LambdaQueryWrapper<DemandCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DemandCollection::getDemandId, demandId)
                .eq(DemandCollection::getUserId, userId);

        // 更新状态为取消
        remove(queryWrapper);

        // 更新需求表计数（-1）
        demandService.updateDemandCollectionCount(demandId, DemandCollectionTypeEnum.cancelCollection, -1);
        return Response.buildSuccess();
    }

    @Override
    public List<String> listDemandIdByUserId(String userId) {
        List<String> demandIdList = new ArrayList<>();
        List<DemandCollection> collections = list(new LambdaQueryWrapper<DemandCollection>()
                .eq(DemandCollection::getUserId, userId)
                .orderByDesc(DemandCollection::getCreateTime)
        );

        for (DemandCollection collection : collections) {
            demandIdList.add(collection.getDemandId());
        }
        return demandIdList;
    }
}